home *** CD-ROM | disk | FTP | other *** search
/ Hardcore Visual Basic 5.0 (2nd Edition) / Hardcore Visual Basic 5.0 - Second Edition (1997)(Microsoft Press).iso / Code / sieve.cls < prev    next >
Text File  |  1997-06-14  |  2KB  |  75 lines

  1. VERSION 1.0 CLASS
  2. BEGIN
  3.   MultiUse = -1  'True
  4. END
  5. Attribute VB_Name = "CSieve"
  6. Attribute VB_GlobalNameSpace = False
  7. Attribute VB_Creatable = True
  8. Attribute VB_PredeclaredId = False
  9. Attribute VB_Exposed = False
  10. Attribute VB_Description = "Sieve of Eratosthenes"
  11. Option Explicit
  12.  
  13. Private af() As Boolean, iCur As Integer
  14. Private iMaxPrime As Integer, cPrime As Integer
  15.  
  16. Private Sub Class_Initialize()
  17.     ' Default size is largest integer
  18.     iMaxPrime = 32766
  19.     ReInitialize
  20. End Sub
  21.  
  22. Sub ReInitialize()
  23.     ReDim af(0 To iMaxPrime)
  24.     iCur = 1: cPrime = 0
  25. End Sub
  26.  
  27. Property Get NextPrime() As Integer
  28.     ' Loop until you find a prime or overflow array
  29.     iCur = iCur + 1
  30.     On Error GoTo OverMaxPrime
  31.     Do While af(iCur)
  32.         iCur = iCur + 1
  33.     Loop
  34.     ' Cancel multiples of this prime
  35.     Dim i As Long
  36.     For i = iCur + iCur To iMaxPrime Step iCur
  37.         af(i) = True
  38.     Next
  39.     ' Count and return it
  40.     cPrime = cPrime + 1
  41.     NextPrime = iCur
  42. OverMaxPrime:       ' Array overflow comes here
  43. End Property
  44.  
  45. Property Get MaxPrime() As Integer
  46.     MaxPrime = iMaxPrime
  47. End Property
  48.  
  49. Property Let MaxPrime(iMaxPrimeA As Integer)
  50.     iMaxPrime = iMaxPrimeA
  51.     ReInitialize
  52. End Property
  53.  
  54. Property Get Primes() As Integer
  55.     Primes = cPrime
  56. End Property
  57.  
  58. Sub AllPrimes(ai() As Integer)
  59.     If LBound(ai) <> 0 Then Exit Sub
  60.     iMaxPrime = UBound(ai)
  61.     cPrime = 0
  62.     Dim i As Integer
  63.     For iCur = 2 To iMaxPrime
  64.         If Not af(iCur) Then    ' Found a prime
  65.             For i = iCur + iCur To iMaxPrime Step iCur
  66.                 af(i) = True    ' Cancel its multiples
  67.             Next
  68.             ai(cPrime) = iCur
  69.             cPrime = cPrime + 1
  70.         End If
  71.     Next
  72.     ReDim Preserve ai(0 To cPrime) As Integer
  73.     iCur = 1
  74. End Sub
  75.